Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

440
Vistas
Palindrome checker does not function properly with "almostomla"

function palindrome(str) {
  const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  const reversed = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  for (let i = 0; i < forward.length; i++) {
    for (let k = reversed.length - 1; k >= 0; k--) {
      if (forward[i] === reversed[k]) {
        return true
      } else {
        return false
      }
    }
  }
}

console.log(palindrome("almostomla"));

Why is this not working?? does my loop just creates a new "s"?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You don't need nested loops, that will compare every character with every other character. You just want to compare the first character with the last character, 2nd character with 2nd-to-last character, and so on. So there should just be a single loop that increments i and decrements k in lock step.

You shouldn't return true when you find a match, because there could be later characters that don't match. Return false when you find a mismatch, and return true if you make it through the loop without returning.

You don't need both forward and reversed variables, since they're the same. Just convert the input string to uppercase once, and use that for both.

You don't need to iterate through the whole string, you can stop when you get to the middle.

function palindrome(str) {
  const upper = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  for (let i = 0, k = upper.length - 1; i < upper.length/2; i++, k--) {
    if (upper[i] !== upper[k]) {
      return false
    }
  }
  return true;
}

console.log(palindrome("almostomla"));
console.log(palindrome("almotomla"));
console.log(palindrome("almottomla"));

about 4 years ago · Juan Pablo Isaza Denunciar

0

You might want this:

function palindrome(str) {
  const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  var n = forward.length
  for (let i = 0; i < n; i++) {
      if (forward[i] !== forward[n-i-1]) {
        return false;
      }
  }
  return true;
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda